var api = require('../../../config/api.js');
var util = require('../../../utils/util.js');
var user = require('../../../utils/user.js');

var app = getApp();
Page({
  data: {
    hasMobile: false,
    isLogin: false
  },
  onLoad: function(options) {
    // 页面初始化 options为页面跳转所带来的参数
    // 页面渲染完成

  },
  onReady: function() {

  },
  onShow: function() {
    // 页面显示
  },
  onHide: function() {
    // 页面隐藏

  },
  onUnload: function() {
    // 页面关闭

  },
  bindPhoneNumber: function(e) {
    if (e.detail.errMsg !== "getPhoneNumber:ok") {
      // 拒绝授权
      return;
    }
    let that = this
    util.request(api.AuthBindPhone, {
      iv: e.detail.iv,
      encryptedData: e.detail.encryptedData
    }, 'POST').then(function(res) {
      
      if (res.errno === 0) {
        wx.showToast({
          title: '绑定手机号码成功',
          icon: 'success',
          duration: 2000
        });
        app.globalData.hasLogin = true;
        wx.navigateBack({
          delta: 1
        })
      }
    });
  },
  wxLogin: function(e) {
    let that = this;
    if (e.detail.userInfo == undefined) {
      app.globalData.hasLogin = false;
      util.showErrorToast('微信登录失败');
      return;
    }

    user.checkLogin()
    .then(res => {
      wx.navigateBack({
        delta: 1
      })
    })
    .catch(() => {
      user.loginByWeixin(e.detail.userInfo).then(res => {
        that.setData({isLogin: true});
        if(res.data.mobile == undefined || res.data.mobile == ''){
          wx.showModal({
            title: '提示',
            content: '未绑定手机号，请点击绑定手机号绑定',
            showCancel: false
          });
           that.setData({hasMobile: false})
        }else{
          that.setData({hasMobile: true})
          app.globalData.hasLogin = true;
          wx.navigateBack({
            delta: 1
          })
        }
      }).catch((err) => {
        app.globalData.hasLogin = false;
        util.showErrorToast('微信登录失败');
      });

    });
  },
  accountLogin: function() {
    wx.navigateTo({
      url: "/pages/auth/accountLogin/accountLogin"
    });
  }
})